<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'

import {
    useMessage,
    NButton, NForm, NFormItem, NInput, NInputNumber, NPopconfirm, NTreeSelect, NTag, NSwitch, NFlex,
    NAvatar, NSelect, NImage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import {useCRUD} from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import {router} from "@/router";

defineOptions({name: '专题页配置'})

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '专题页配置',
  initForm: {},
  doCreate: api.createMiniTopic,
  doUpdate: api.updateMiniTopic,
  doDelete: api.deleteMiniTopic,
  refresh: () => $table.value?.handlerefresh(),
})
onMounted(() => {
  $table.value?.handleSearch()
})

function on_add(){
  router.push("/mini/mini_settings/topic_add")
}

function on_edit(row){
  router.push({ path: '/mini/mini_settings/topic_add', query: { id: row.id } });
}

// 修改禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.is_active = row.is_active === false
  row.publishing = false
  try {
    await api.updateMiniTopic(row)
    $message?.success(row.is_active ? '已取消禁用' : '已禁用')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.is_active = row.is_active === false
  } finally {
    row.publishing = false
  }
}
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 40,
    align: 'center',
    ellipsis: {tooltip: true},
  },
  {
    title: '名称',
    key: 'name',
    width: 'auto',
    align: 'center',
    ellipsis: {tooltip: true},
    fixed: 'left',
  },


  {
    title: '禁用',
    key: 'is_active',
    width: '100',
    align: 'center',
    fixed: 'right',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.is_active,
        loading: !!row.publishing,
        checkedValue: false,
        uncheckedValue: true,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '创建时间',
    key: 'created_at',
    align: 'center',
    width: 'auto',
    ellipsis: {tooltip: true},
  },
  {
    title: '操作',
    key: 'actions',
    width: 'auto',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
            h(
                NButton,
                {
                  size: 'small',
                  type: 'primary',
                  style: 'margin-right: 8px;',
                  onClick: () => {
                    on_edit(row)
                  },
                },
                {
                  default: () => '编辑',
                  icon: renderIcon('material-symbols:edit', {size: 16}),
                }
            ),
            [[vPermission, 'post/api/mini/settings/update']]
        ),
        h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete({data_id: row.id}, false),
              onNegativeClick: () => {
              },
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'error',
                          },
                          {
                            default: () => '删除',
                            icon: renderIcon('material-symbols:delete-outline', {size: 16}),
                          }
                      ),
                      [[vPermission, 'delete/api/mini/settings/delete']]
                  ),
              default: () => h('div', {}, '确定删除该数据吗?'),
            }
        ),
      ]
    },
  },
]
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="专题页">
    <template #action>
      <div>
        <NButton v-permission="'post/api/mini/settings/create'" class="float-right mr-15" type="primary"
                 @click="on_add">
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5"/>
          新建专题页
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable ref="$table" v-model:query-items="queryItems" :columns="columns" :get-data="api.getMiniTopic">
      <template #queryBar>
        <QueryBarItem label="专题名称" :label-width="80">
          <NInput v-model:value="queryItems.name" clearable type="text" placeholder="请输入名称"
                  @keypress.enter="$table?.handleSearch()"/>
        </QueryBarItem>
      </template>
    </CrudTable>
  </CommonPage>
</template>
